<?php
class UsersController extends Controller
{
	public $layout='//layouts/admin/main';

	public function init()
	{
			Yii::app()->user->loginUrl = array('/admin/site/login');
			parent::init();
	}

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('login','logout'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'index', 'view', 'cciht', 'delete', 'approve', 'decline', 'schoolmember', 'paymentconfirm', 'paymentdecline', 'makehash'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
  
  public function actionMakeHash(){
    $users = Users::model()->findAll();
    
    foreach($users as $user){
      $user->password = md5($user->password);
      $user->save();
    }
    
    print_r('Success!');
  }

  public function actionSchoolMember()
  {
    $user = Users::model()->find('id = :id', array(':id' => $_GET['id']));
    $schools = School::model()->findAll('user_id = :user_id', array(':user_id' => $user->id));
    $data = School::model()->find('user_id = :user_id', array(':user_id' => $user->id));
    $this->render('school', array(
      'user' => $user,
      'schools' => $schools,
      'data' => $data,
    ));
  }

  public function actionPaymentConfirm(){
    /*Change this to false in production -------------------*/
    $debug_mode = true;
    /*--------------------------------------------------------------------*/

    $user = Users::model()->find('id = :id', array(':id' => $_GET['id']));
    $user->payment_confirm = Users::STATUS_PAID;
    if($user->save()){
      //generate school membership
      $school = School::model()->find('user_id = :user_id', array(':user_id' => $_GET['id']));
      $membership = explode('/',$school->membership);

      //generate username
      $criteria = new CDbCriteria;
      $criteria -> condition = "membership LIKE '%tmp%'";
      $criteria -> order = 'id DESC';
      $criteria -> limit = 1;

      $tmp = School::model()->find($criteria);
      $str = explode("/", $tmp->membership);

      $user->username = ((int)$str[3]+1);
      $user->save();

      $school->membership = $membership[0]."/".$membership[1]."/".$membership[2]."/".$user->username;

      // extend membership
      $cur_year = strftime('%Y');
      $extend = $user->membership_extend;
      $user->expired_date = $cur_year+$extend.strftime('-%m-%d');
      $user->save();

      if($debug_mode == false){
        // send email
        $email = Yii::app()->email;
        $email->to = $user->email;
        $email->subject = 'ACSI - Thank you for registering with us';
        $email->message = 'Our system automatically created a new password for you. Please use this login information the next time you login.
          Username: '.$user->username.'
          Password: '.$user->password_salt.'
          You should change this password the next time you login. You can change your password in the account settings. ';
        $email->send();
      }

      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'This member payment has been confirmed.');

      $this->redirect(bu('admin/users/schoolmember?id='.$_GET['id']));
    }
  }

  public function actionPaymentDecline(){
    $user = Users::model()->find('id = :id', array(':id' => $_GET['id']));
    $user->payment_confirm = Users::STATUS_NOT_PAID;
    if($user->save()){

      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'Successfully mark this user not paid yet.');

      $this->redirect(bu('admin/users/schoolmember?id='.$_GET['id']));
    }
  }

  public function actionApprove()
  {
    /*Change this to false in production -------------------*/
    $debug_mode = true;
    /*--------------------------------------------------------------------*/

    if(isset($_GET['member']))
    {
      $user = Users::model()->find('id = :id', array(':id' => $_GET['member']));
    }
    else
    {
      $user = Users::model()->find('id = :id', array(':id' => $_GET['id']));
    }
    $user->status = Users::STATUS_APPROVED;
    $user->modified_at = date('Y-m-d H:i:s');

    if($user->save()){
      if($debug_mode == false){
        // send email
        $email = Yii::app()->email;
        $email->to = $user->email;
        $email->subject = 'ACSI - Only one more step to join us!';
        $email->message = 'Your account has been approved, please confirm your payment immediatly.';
        $email->send();
      }

      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have approved a member.');
    }
    else{
      Yii::app()->user->setFlash('error', 'Error');
      Yii::app()->user->setFlash('content', 'Please try again later.');
    }

    if(isset($_GET['member']))
    {
      //$this->redirect(bu('admin/members?member='.$_GET['member']));
      $this->redirect(bu('admin/members?member='.$user->member_id));
    }
    else
    {
      // $this->redirect(bu("admin/programs?id=".$user->program_id));
      $this->redirect(bu('admin/members?member='.$user->member_id));
    }
  }

  public function actionDecline()
  {
    /*Change this to false in production -------------------*/
    $debug_mode = true;
    /*--------------------------------------------------------------------*/

     if(isset($_GET['member']))
    {
      $user = Users::model()->find('id = :id', array(':id' => $_GET['member']));
    }
    else
    {
      $user = Users::model()->find('id = :id', array(':id' => $_GET['id']));
    }
    $user->status = Users::STATUS_REJECT;
    $user->modified_at = date('Y-m-d H:i:s');

    if($user->save()){
      if($debug_mode == false){
        // send email
        $email = Yii::app()->email;
        $email->to = $user->email;
        $email->subject = 'ACSI - Your membership has been denied.';
        $email->message = 'We\'re so sorry, your membership has been denied. Please apply again later or contact us to find out more.';
        $email->send();

        Yii::app()->user->setFlash('success', 'Success');
        Yii::app()->user->setFlash('content', 'You have decline a member.');
      }
    }
    else{
      Yii::app()->user->setFlash('error', 'Error');
      Yii::app()->user->setFlash('content', 'Please try again later.');
    }

    if(isset($_GET['member']))
    {
      //$this->redirect(bu('admin/members?member='.$_GET['member']));
      $this->redirect(bu('admin/members?member='.$user->member_id));
    }
    else
    {
      // $this->redirect(bu("admin/programs?id=".$user->program_id));
      $this->redirect(bu('admin/members?member='.$user->member_id));
    }
  }

  public function actionCciht()
  {
    $user = Users::model()->with('cciht')->findByPk($_GET['id']);

    $this->render('cciht', array(
      'user' => $user,
    ));
  }

	public function actionView($id)
	{
    $connection=Yii::app()->db;

    $user = Users::model()->find('id = :id', array(':id' => $id));
    $program = Programs::model()->find('id = :program_id', array(':program_id' => $user->program_id));
    // $model = ${strtolower($program->name)}::model()->findAll();
    $var = strtolower($program->name);
    $model = CActiveRecord::model($var)->find('user_id = :user_id ', array(':user_id' => $id));

		$this->render($var,array(
			'model' => $model,
		));
	}

	public function actionCreate()
	{
		$model=new Users;

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
      $model->modified_at = date('Y-m-d H:i:s');
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
      $model->modified_at = date('Y-m-d H:i:s');
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
    $id = $_GET['id'];
    $user = Users::model()->find('id = :id', array(':id' => $id));

    // determine detail user in which table
    if($user->program_id)
    {
      $program = Programs::model()->find('id = :program_id', array(':program_id' => $user->program_id));
      $slug = strtolower($program->name);
    }
    else if($user->member_id)
    {
      $member = Members::model()->find('id = :member_id', array(':member_id' => $user->member_id));
      $slug = strtolower($member->slug);
    }

    // find detail user in on of many tables & delete record
    $model = CActiveRecord::model($slug)->find('user_id = :user_id', array(':user_id' => $user->id));
    $model->delete();

    $user->delete();
    $this->redirect(bu('admin/'));
	}

	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Users');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
